'use strict';
const db = uniCloud.database();
const crypto = require('crypto');

// 密码加密函数
function encryptPassword(password) {
	return crypto.createHash('sha256').update(password).digest('hex');
}

// 验证Token
function verifyToken(token) {
	try {
		const payload = JSON.parse(Buffer.from(token, 'base64').toString());
		if (payload.exp < Date.now()) {
			return null; // Token已过期
		}
		return payload;
	} catch (error) {
		return null;
	}
}

exports.main = async (event, context) => {
	const { action, userData, userId, page = 1, limit = 10 } = event;
	
	// 管理员用户管理操作，无需Token验证
	
	try {
		const userCollection = db.collection('user');
		
		switch (action) {
			// 获取用户列表
			case 'list':
				const skip = (page - 1) * limit;
				const listResult = await userCollection
					.field({
						password: false // 不返回密码字段
					})
					.orderBy('create_date', 'desc')
					.skip(skip)
					.limit(limit)
					.get();
				
				// 获取总数
				const countResult = await userCollection.count();
				
				return {
					code: 0,
					message: '获取用户列表成功',
					data: {
						list: listResult.data,
						total: countResult.total,
						page: page,
						limit: limit
					}
				};
				
			// 创建用户
			case 'create':
				if (!userData || !userData.username || !userData.password || !userData.role) {
					return {
						code: 400,
						message: '用户名、密码和角色不能为空'
					};
				}
				
				// 验证角色类型
				if (!['user', 'admin'].includes(userData.role)) {
					return {
						code: 400,
						message: '无效的角色类型'
					};
				}
				
				// 检查用户名是否已存在
				const existUser = await userCollection
					.where({ username: userData.username })
					.get();
				
				if (existUser.data.length > 0) {
					return {
						code: 400,
						message: '用户名已存在'
					};
				}
				
				// 创建新用户
				const newUser = {
					username: userData.username,
					password: encryptPassword(userData.password),
					role: userData.role,
					nickname: userData.nickname || userData.username,
					email: userData.email || '',
					mobile: userData.mobile || '',
					avatar: userData.avatar || '',
					status: userData.status || 'active',
					register_date: Date.now(),
					register_ip: context.CLIENTIP,
					last_login_date: null,
					last_login_ip: ''
				};
				
				const createResult = await userCollection.add(newUser);
				
				return {
					code: 0,
					message: '用户创建成功',
					data: {
						userId: createResult.id
					}
				};
				
			// 更新用户
			case 'update':
				if (!userId) {
					return {
						code: 400,
						message: '用户ID不能为空'
					};
				}
				
				if (!userData) {
					return {
						code: 400,
						message: '更新数据不能为空'
					};
				}
				
				// 构建更新数据
				const updateData = {
					update_date: Date.now()
				};
				
				// 只更新提供的字段
				if (userData.nickname !== undefined) updateData.nickname = userData.nickname;
				if (userData.email !== undefined) updateData.email = userData.email;
				if (userData.mobile !== undefined) updateData.mobile = userData.mobile;
				if (userData.avatar !== undefined) updateData.avatar = userData.avatar;
				if (userData.status !== undefined) updateData.status = userData.status;
				if (userData.role !== undefined && ['user', 'admin'].includes(userData.role)) {
					updateData.role = userData.role;
				}
				
				// 如果提供了新密码，则加密后更新
				if (userData.password) {
					updateData.password = encryptPassword(userData.password);
				}
				
				const updateResult = await userCollection.doc(userId).update(updateData);
				
				return {
					code: 0,
					message: '用户更新成功',
					data: {
						updated: updateResult.updated
					}
				};
				
			// 删除用户
			case 'delete':
				if (!userId) {
					return {
						code: 400,
						message: '用户ID不能为空'
					};
				}
				
				// 管理员可以删除任何用户（包括自己）
				
				const deleteResult = await userCollection.doc(userId).remove();
				
				return {
					code: 0,
					message: '用户删除成功',
					data: {
						deleted: deleteResult.deleted
					}
				};
				
			// 获取单个用户详情
			case 'detail':
				if (!userId) {
					return {
						code: 400,
						message: '用户ID不能为空'
					};
				}
				
				const detailResult = await userCollection
					.doc(userId)
					.field({
						password: false // 不返回密码字段
					})
					.get();
				
				if (detailResult.data.length === 0) {
					return {
						code: 404,
						message: '用户不存在'
					};
				}
				
				return {
					code: 0,
					message: '获取用户详情成功',
					data: detailResult.data[0]
				};
				
			default:
				return {
					code: 400,
					message: '无效的操作类型'
				};
		}
		
	} catch (error) {
		console.error('用户管理操作错误:', error);
		return {
			code: 500,
			message: '服务器内部错误'
		};
	}
};